//
//  StatusRefreshControl.swift
//  Weibo10
//
//  Created by Leon on 15/10/22.
//  Copyright © 2015年 Leon. All rights reserved.
//

import UIKit

class StatusRefreshControl: UIRefreshControl {
    
///  重写刷新函数
    override func beginRefreshing() {
        super.beginRefreshing()
        refreshPullView.startAnimation()
    }
    
    override func endRefreshing() {
        super.endRefreshing()
        refreshPullView.stopAnimation()
    }

    // MARK: - KVO 监听方法
    /**
    1. 始终待在屏幕上
    2. 下拉的时候，frame 的 y 一直变小，相反（向上推）一直变大
    3. 默认的 y 是 0
    */

    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        let tippingPoint = frame.origin.y
        if tippingPoint > 0 {
            return
        }

        // 判断是否正在刷新
        if refreshing {
            refreshPullView.startAnimation()
            return
        }
        
        if tippingPoint > -60 && refreshPullView.rotationFlag {
            print("向上")
            refreshPullView.rotationFlag = false
        } else if tippingPoint <= -60 && !refreshPullView.rotationFlag {
            print("向下")
            refreshPullView.rotationFlag = true
            
        }
        
    }
    
    //MARK: - 构造函数
    override init() {
        super.init()
        setupUI()
    }
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupUI()
    }
    
    //MARK: - 设置UI
    private func setupUI() {
        
        // 添加控件
        addSubview(refreshPullView)
        
        // 自动布局
        refreshPullView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(self.snp_center)
            make.size.equalTo(refreshPullView.bounds.size)
        }
        
        // 使用 KVO 监听位置变化 - 主队列，当主线程有任务，就不调度队列中的任务执行
        // 让当前运行循环中所有代码执行完毕后，运行循环结束前，开始监听
        // 方法触发会在下一次运行循环开始！
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
            self.addObserver(self,
                forKeyPath: "frame",
                options: [],
                context: nil)
        }
    }
    
    deinit {
        
        // 移除监听
        removeObserver(self, forKeyPath: "frame")
    }
    
    /// 刷新视图
    private lazy var refreshPullView = RefreshView.loadRefreshView()
    

}

/// 刷新视图 - 负责处理`动画显示`
class RefreshView: UIView {
    
    /// 下载旋转标记
    var rotationFlag: Bool = false {
        didSet {
            
            rotatePullView()
        }
    }
    
    @IBOutlet weak var loadingView: UIImageView!
    @IBOutlet weak var pullView: UIImageView!
    @IBOutlet weak var pullAllView: UIView!
    
    //MARK: - 加载xib
    class func loadRefreshView() -> RefreshView {
        
        let nib = UINib(nibName: "refreshView", bundle: nil)
        
        return nib.instantiateWithOwner(nil, options: nil)[0] as! RefreshView
    }
    
///  箭头旋转
    private func rotatePullView() {
        
        var angle = CGFloat(M_PI)
        angle += rotationFlag ? -0.00000001 : 0.00000001
        // 旋转动画，特点：顺时针优先 + `就近原则`
        UIView.animateWithDuration(0.5) { () -> Void in
            
            self.pullView.transform = CGAffineTransformRotate(self.pullView.transform, angle)
        }
    }
    
    ///  旋转函数
    private func startAnimation() {
        
        pullAllView.hidden = true
        
        let key = "rotateLoadingView"
        print("加载动画播放")
        if loadingView.layer.animationForKey(key) != nil {
            return
        }
        let anim = CABasicAnimation(keyPath: "transform.rotation")
        anim.toValue = 2 * M_PI
        anim.repeatCount = MAXFLOAT
        anim.duration = 0.5
        anim.removedOnCompletion = false
        loadingView.layer.addAnimation(anim, forKey: key)
    }
    
    private func stopAnimation() {
        
        pullAllView.hidden = false
        
        loadingView.layer.removeAllAnimations()
    }
}






